package com.changgou.oauth.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.oauth.service.UserLoginService;
import com.changgou.oauth.util.AuthToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
 * @ClassName UserController
 * @Description 用户登录
 * @Author 洛尘
 * @Date 18:17 2019/11/21
 * @Version 2.1
 **/
@RestController
@RequestMapping("/user")
public class UserLoginController {

    @Autowired(required = false)
    private UserLoginService userLoginService;

    //客户端id
    @Value("${auth.clientId}")
    private String clientId;

    //客户端秘钥
    @Value("${auth.clientSecret}")
    private String clientSecret;

    /**
     * 用户登录
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/login")
    public Result login(String username, String password, HttpServletResponse response) throws UnsupportedEncodingException {
        try {
            //设置加密为密码授权
            String grant_type = "password";
            //登录认证
            AuthToken authToken = userLoginService.login(username,password,clientId,clientSecret,grant_type);

            String accessToken = authToken.getAccessToken();
            Cookie cookie = new Cookie("Authorization",accessToken);
            cookie.setDomain("localhost");
            cookie.setPath("/");
            response.addCookie(cookie);
            return new Result(true, StatusCode.OK,"登录成功",accessToken);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return new Result(false,StatusCode.LOGINERROR,"登录失败");
    }


}
